package org.now.ypos.exception;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author wl
 * @since 2020.11.11
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 请求方式不支持
     *
     * @param e HttpRequestMethodNotSupportedException
     * @return ResponseEntity
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public final ResponseEntity<String> handleException(final HttpRequestMethodNotSupportedException e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).body(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     *
     * @param e RuntimeException
     * @return ResponseEntity
     */
    @ExceptionHandler(RuntimeException.class)
    public final ResponseEntity<String> handleRuntimeException(final RuntimeException e) {
        LOGGER.error("运行时异常:", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(("RuntimeException: ".concat(e.getMessage())));
    }

    /**
     * 系统异常
     *
     * @param e Exception
     * @return ResponseEntity
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(final Exception e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(("Exception: ".concat(e.getMessage())));
    }


}
